<template>
  <div class="page-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon size="20" class="header-icon"><Key /></el-icon>
            <h3>权限管理</h3>
            <span class="header-desc">管理系统权限和API接口</span>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="showAddPermission" :icon="Plus" plain>
              新增权限
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="权限名称">
            <el-input 
              v-model="searchForm.permissionName" 
              placeholder="请输入权限名称" 
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="权限编码">
            <el-input 
              v-model="searchForm.permissionCode" 
              placeholder="请输入权限编码" 
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="权限类型">
            <el-select v-model="searchForm.permissionType" placeholder="请选择权限类型" clearable style="width: 120px;">
              <el-option label="目录" value="M" />
              <el-option label="菜单" value="C" />
              <el-option label="按钮" value="F" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadPermissions" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="permissions"
        style="width:100%;"
        row-key="permissionId"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="permission-table"
        v-loading="loading"
        element-loading-text="正在加载..."
        element-loading-background="rgba(255, 255, 255, 0.6)"
      >
        <el-table-column prop="permissionName" label="权限名称" min-width="200">
          <template #default="scope">
            <div class="permission-name-cell">
              <el-icon><component :is="getPermIcon(scope.row.permissionType)" /></el-icon>
              <span>{{ scope.row.permissionName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="permissionCode" label="权限编码" min-width="150" />
        <el-table-column prop="permissionType" label="权限类型" width="100">
          <template #default="scope">
            <el-tag :type="getPermTagType(scope.row.permissionType)">
              {{ getPermTypeText(scope.row.permissionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="apiPath" label="API路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.method" :type="getMethodTagType(scope.row.method)" size="small">
              {{ scope.row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editPermission(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deletePermission(scope.row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无权限数据" />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadPermissions"
          @current-change="loadPermissions"
        />
      </div>
    </el-card>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog 
      v-model="showAdd" 
      :title="form.permissionId ? '编辑权限' : '新增权限'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称" prop="permissionName">
              <el-input v-model="form.permissionName" placeholder="请输入权限名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限编码" prop="permissionCode">
              <el-input v-model="form.permissionCode" placeholder="请输入权限编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
                         <el-form-item label="权限类型" prop="permissionType">
               <el-radio-group v-model="form.permissionType">
                 <el-radio value="M">目录</el-radio>
                 <el-radio value="C">菜单</el-radio>
                 <el-radio value="F">按钮</el-radio>
               </el-radio-group>
             </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="API路径" prop="apiPath">
              <el-input v-model="form.apiPath" placeholder="请输入API路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求方法" prop="method">
              <el-select v-model="form.method" placeholder="请选择请求方法" style="width: 100%;">
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
                <el-option label="PATCH" value="PATCH" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="permissionTreeOptions"
            :props="{ children: 'children', label: 'permissionName', value: 'permissionId' }"
            placeholder="请选择上级权限"
            style="width: 100%;"
            :render-after-expand="false"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="菜单ID" prop="menuId">
          <el-input-number v-model="form.menuId" :min="0" placeholder="关联菜单ID" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入权限描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAdd=false">取消</el-button>
          <el-button type="primary" @click="savePermission" :loading="saving">
            {{ saving ? '保存中...' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Key, Plus, Search, Refresh, Edit, Delete,
  Menu, Lock, Document
} from '@element-plus/icons-vue'

const permissions = ref([])
const showAdd = ref(false)
const form = ref({})
const formRef = ref()
const saving = ref(false)
const permissionTreeOptions = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = ref({
  permissionName: '',
  permissionCode: '',
  permissionType: ''
})

// 分页
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表单验证规则
const formRules = {
  permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  permissionCode: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
  permissionType: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

// 获取权限图标
const getPermIcon = (permType) => {
  const iconMap = {
    'M': Menu,
    'C': Document,
    'F': Lock
  }
  return iconMap[permType] || Lock
}

// 获取权限标签类型
const getPermTagType = (permType) => {
  const typeMap = {
    'M': 'primary',
    'C': 'success',
    'F': 'warning'
  }
  return typeMap[permType] || 'info'
}

// 获取权限类型文本
const getPermTypeText = (permType) => {
  const typeMap = {
    'M': '目录',
    'C': '菜单',
    'F': '按钮'
  }
  return typeMap[permType] || '权限'
}

// 获取请求方法标签类型
const getMethodTagType = (method) => {
  const typeMap = {
    'GET': 'primary',
    'POST': 'success',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return typeMap[method] || 'info'
}

const loadPermissions = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      ...searchForm.value
    }

    console.log('请求参数:', params)
    const res = await request.get('/system/permissions', { params })
    console.log('API响应数据:', res)

    const payload = res.data ?? res
    const records = payload?.records ?? payload?.data?.records ?? payload?.data ?? []
    const total = payload?.total ?? payload?.data?.total ?? 0
    permissions.value = buildPermissionTree(Array.isArray(records) ? records : [])
    pagination.value.total = total
    console.log('构建的权限树:', permissions.value)
  } catch (error) {
    console.error('加载权限失败:', error)
  } finally {
    loading.value = false
  }
}

const buildPermissionTree = (permissions) => {
  const tree = []
  const map = {}
  
  // 创建映射
  permissions.forEach(perm => {
    map[perm.permissionId] = { ...perm, children: [] }
  })
  
  // 构建树结构
  permissions.forEach(perm => {
    if (perm.parentId && perm.parentId !== 0) {
      if (map[perm.parentId]) {
        map[perm.parentId].children.push(map[perm.permissionId])
      }
    } else {
      tree.push(map[perm.permissionId])
    }
  })
  
  return tree
}

const loadPermissionTreeOptions = async () => {
  try {
    const res = await request.get('/system/permissions/tree')
    const payload = res.data ?? res
    permissionTreeOptions.value = [
      { permissionId: 0, permissionName: '根权限', children: (payload?.data ?? payload) || [] }
    ]
  } catch (error) {
    console.error('加载权限树失败:', error)
    ElMessage.error('加载权限树失败')
  }
}

const resetSearch = () => {
  searchForm.value = { permissionName: '', permissionCode: '', permissionType: '' }
  pagination.value.pageNum = 1
  loadPermissions()
}

const showAddPermission = () => {
  form.value = { 
    permissionType: 'F', 
    sort: 0, 
    parentId: 0,
    method: 'GET' 
  }
  showAdd.value = true
  loadPermissionTreeOptions()
}

const savePermission = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  saving.value = true
  
  try {
    if (form.value.permissionId) {
      await request.put('/system/permissions', form.value)
      ElMessage.success('修改成功')
    } else {
      await request.post('/system/permissions', form.value)
      ElMessage.success('添加成功')
    }
    showAdd.value = false
    loadPermissions()
  } catch (error) {
    console.error('保存权限失败:', error)
  } finally {
    saving.value = false
  }
}

const editPermission = (row) => {
  form.value = { ...row }
  showAdd.value = true
  loadPermissionTreeOptions()
}

const deletePermission = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除权限"${row.permissionName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete('/system/permissions', { data: [row.permissionId] })
    ElMessage.success('删除成功')
    loadPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
    }
  }
}

onMounted(() => {
  loadPermissions()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.page-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  color: #409eff;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-weight: 600;
}

.header-desc {
  color: #909399;
  font-size: 14px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.permission-table {
  margin-bottom: 20px;
}

.permission-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table__row) {
  transition: background-color 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-button--small) {
  margin-left: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style> 